import { useState, useEffect } from 'react'
import apiService from '../utils/api.js'
import '../styles/pages.css'
import PlaylistItem from '../components/PlaylistItem.jsx'
import AddToPlaylistModal from '../components/AddToPlaylistModal.jsx'
import SongCard from '../components/SongCard.jsx'

function Discover({ playSong, playPlaylist }) {
  const [selectedCategory, setSelectedCategory] = useState('all')
  const [categories, setCategories] = useState([
    { id: 'all', name: '全部' }
  ])
  const [songs, setSongs] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [loadingMore, setLoadingMore] = useState(false)
  const [playlists, setPlaylists] = useState([])
  const [playlistsLoading, setPlaylistsLoading] = useState(true)
  const [playlistsError, setPlaylistsError] = useState(null)
  const [showAddToPlaylistModal, setShowAddToPlaylistModal] = useState(false)
  const [selectedSong, setSelectedSong] = useState(null)
  
  // 获取分类数据
  const fetchCategories = async () => {
    try {
      const response = await apiService.getCategories()
      if (response.code === 200 && response.data) {
        // 添加'全部'分类作为第一个选项
        setCategories([
          { id: 'all', name: '全部' },
          ...response.data.map(cat => ({ id: cat.id.toString(), name: cat.name }))
        ])
      }
    } catch (err) {
      console.error('获取分类失败:', err)
      setError('获取分类失败')
      // 出错时使用默认分类
      setCategories([
        { id: 'all', name: '全部' },
        { id: 'pop', name: '流行' },
        { id: 'rock', name: '摇滚' },
        { id: 'folk', name: '民谣' },
        { id: 'electronic', name: '电子' },
        { id: 'classical', name: '古典' }
      ])
    }
  }
  
  // 获取歌曲数据
  const fetchSongs = async (page = 1, isLoadMore = false) => {
    try {
      // 设置加载状态
      if (isLoadMore) {
        setLoadingMore(true)
      } else {
        setLoading(true)
      }
      
      const pageSize = 12; // 每页显示12首歌曲
      const params = {
        categoryId: selectedCategory === 'all' ? undefined : selectedCategory,
        page,
        limit:pageSize
      };
      
      // 尝试获取推荐歌曲
      const response = await apiService.getRecommendedSongs(params)
      
      let newSongs = [];
      if (response.code === 200 && response.data.data) {
        newSongs = response.data.data;
        // 判断是否还有更多歌曲
        setHasMore(newSongs.length === pageSize);
      } else {
        // 如果推荐歌曲接口不可用，尝试获取热门歌曲
        const topResponse = await apiService.getTopSongs(params)
        if (topResponse.code === 200 && topResponse.data) {
          newSongs = topResponse.data;
          setHasMore(newSongs.length === pageSize);
        } else {
          // 如果都不可用，使用模拟数据
          // 为了演示分页效果，生成不同ID的模拟数据
          newSongs = generateMockSongs(page, pageSize);
          // 模拟数据最多3页
          setHasMore(page < 3);
        }
      }
      
      // 更新歌曲列表
      if (isLoadMore) {
        setSongs(prevSongs => [...prevSongs, ...newSongs]);
      } else {
        setSongs(newSongs);
      }
    } catch (err) {
      console.error('获取歌曲失败:', err)
      setError('获取歌曲失败')
      // 出错时使用模拟数据
      const mockSongs = generateMockSongs(page, 12);
      if (isLoadMore) {
        setSongs(prevSongs => [...prevSongs, ...mockSongs]);
      } else {
        setSongs(mockSongs);
      }
      setHasMore(page < 3); // 模拟数据最多3页
    } finally {
      // 重置加载状态
      if (isLoadMore) {
        setLoadingMore(false)
      } else {
        setLoading(false)
        setCurrentPage(1); // 切换分类时重置为第一页
      }
    }
  }
  
  // 生成模拟歌曲数据
  const generateMockSongs = (page, pageSize) => {
    const mockData = [
      { title: '晴天', artist: '周杰伦', cover: 'https://via.placeholder.com/300?text=晴天', category: 'pop' },
      { title: '海阔天空', artist: 'Beyond', cover: 'https://via.placeholder.com/300?text=海阔天空', category: 'rock' },
      { title: '南山南', artist: '马頔', cover: 'https://via.placeholder.com/300?text=南山南', category: 'folk' },
      { title: 'Faded', artist: 'Alan Walker', cover: 'https://via.placeholder.com/300?text=Faded', category: 'electronic' },
      { title: '月光奏鸣曲', artist: '贝多芬', cover: 'https://via.placeholder.com/300?text=月光奏鸣曲', category: 'classical' },
      { title: '告白气球', artist: '周杰伦', cover: 'https://via.placeholder.com/300?text=告白气球', category: 'pop' },
      { title: '起风了', artist: '买辣椒也用券', cover: 'https://via.placeholder.com/300?text=起风了', category: 'pop' },
      { title: '夜曲', artist: '周杰伦', cover: 'https://via.placeholder.com/300?text=夜曲', category: 'pop' },
      { title: '成都', artist: '赵雷', cover: 'https://via.placeholder.com/300?text=成都', category: 'folk' },
      { title: '可惜没如果', artist: '林俊杰', cover: 'https://via.placeholder.com/300?text=可惜没如果', category: 'pop' },
      { title: '不再犹豫', artist: 'Beyond', cover: 'https://via.placeholder.com/300?text=不再犹豫', category: 'rock' },
      { title: 'Shape of You', artist: 'Ed Sheeran', cover: 'https://via.placeholder.com/300?text=Shape+of+You', category: 'pop' }
    ];
    
    // 根据页码生成不同ID的歌曲数据
    const startIndex = (page - 1) * pageSize;
    const songs = [];
    
    for (let i = 0; i < pageSize; i++) {
      const mockIndex = (startIndex + i) % mockData.length;
      const mockSong = mockData[mockIndex];
      
      // 为了演示效果，确保ID唯一
      songs.push({
        ...mockSong,
        id: startIndex + i + 1
      });
    }
    
    // 根据当前选中的分类过滤
    if (selectedCategory !== 'all') {
      return songs.filter(song => song.category === selectedCategory);
    }
    
    return songs;
  }
  
  // 加载更多歌曲
  const loadMoreSongs = async () => {
    if (loadingMore || !hasMore) return;
    
    const nextPage = currentPage + 1;
    await fetchSongs(nextPage, true);
    setCurrentPage(nextPage);
  }
  
  // 获取推荐歌单数据
  const fetchPlaylists = async () => {
    try {
      setPlaylistsLoading(true)
      // 获取官方推荐歌单（isOfficial=true）
      const response = await apiService.getOfficialPlaylists({ limit: 4 })
      if (response.code === 200 && response.data && Array.isArray(response.data)) {
        setPlaylists(response.data)
      } else if (response.code === 200 && response.data && response.data.data) {
        setPlaylists(response.data.data)
      } else {
        // 如果API不可用，使用模拟数据
        setPlaylists([
          { id: 1, name: '热门流行', description: '精选流行音乐', coverImageUrl: 'https://via.placeholder.com/300?text=热门流行', songCount: 32 },
          { id: 2, name: '古典音乐精选', description: '古典音乐经典作品', coverImageUrl: 'https://via.placeholder.com/300?text=古典精选', songCount: 25 },
          { id: 3, name: '摇滚盛宴', description: '震撼摇滚歌曲合集', coverImageUrl: 'https://via.placeholder.com/300?text=摇滚盛宴', songCount: 40 },
          { id: 4, name: '民谣小调', description: '治愈系民谣歌曲', coverImageUrl: 'https://via.placeholder.com/300?text=民谣小调', songCount: 28 }
        ])
      }
    } catch (err) {
      console.error('获取推荐歌单失败:', err)
      setPlaylistsError('获取推荐歌单失败')
      // 出错时使用模拟数据
      setPlaylists([
        { id: 1, name: '热门流行', description: '精选流行音乐', coverImageUrl: 'https://via.placeholder.com/300?text=热门流行', songCount: 32 },
        { id: 2, name: '古典音乐精选', description: '古典音乐经典作品', coverImageUrl: 'https://via.placeholder.com/300?text=古典精选', songCount: 25 },
        { id: 3, name: '摇滚盛宴', description: '震撼摇滚歌曲合集', coverImageUrl: 'https://via.placeholder.com/300?text=摇滚盛宴', songCount: 40 },
        { id: 4, name: '民谣小调', description: '治愈系民谣歌曲', coverImageUrl: 'https://via.placeholder.com/300?text=民谣小调', songCount: 28 }
      ])
    } finally {
      setPlaylistsLoading(false)
    }
  }

  // 打开添加到歌单模态框
  const openAddToPlaylistModal = (song) => {
    setSelectedSong(song)
    setShowAddToPlaylistModal(true)
  }

  // 关闭添加到歌单模态框
  const closeAddToPlaylistModal = () => {
    setShowAddToPlaylistModal(false)
    setSelectedSong(null)
  }

  // 添加歌曲到歌单成功后的回调函数
  const handleAddToPlaylistSuccess = () => {
    // 可以在这里添加成功后的额外逻辑
    console.log('歌曲成功添加到歌单')
  }

  // 组件加载时获取数据
  useEffect(() => {
    fetchCategories()
    fetchSongs()
    fetchPlaylists()
  }, [])
  
  // 当选中的分类改变时，重新获取歌曲数据
  useEffect(() => {
    fetchSongs()
  }, [selectedCategory])
  
  
  
  return (
    <div className="discover-page">
      <div className="section-header">
        <h2>发现音乐</h2>
        <p>探索不同风格的音乐，发现您喜爱的新歌曲</p>
      </div>
      
      {/* 分类标签 */}
      <div className="category-tabs">
        {categories.map((category) => (
          <button
            key={category.id}
            className={`category-tab ${selectedCategory === category.id ? 'active' : ''}`}
            onClick={() => setSelectedCategory(category.id)}
          >
            {category.name}
          </button>
        ))}
      </div>
      
      {/* 错误信息显示 */}
      {error && (
        <div className="error-message">
          {error}
        </div>
      )}
      
      {/* 加载状态 */}
      {loading ? (
        <div className="loading-container">
          <div className="loading-spinner"></div>
          <p>加载中...</p>
        </div>
      ) : (
        <>
          {/* 歌曲列表 */}
          <div className="song-grid">
            {songs.length > 0 ? (
              songs.map((song) => (
                <SongCard
                  key={song.id}
                  song={song}
                  onClick={playSong}
                  onAddToPlaylist={openAddToPlaylistModal}
                />
              ))
            ) : (
              <div className="empty-state">
                <p>暂无歌曲</p>
              </div>
            )}
          </div>
          
          {/* 加载更多按钮 */}
          {!loading && songs.length > 0 && (
            <div className="load-more-container">
              {loadingMore ? (
                <div className="loading-spinner"></div>
              ) : hasMore ? (
                <button 
                  className="btn-load-more" 
                  onClick={loadMoreSongs}
                >
                  加载更多
                </button>
              ) : (
                <p className="no-more-songs">没有更多歌曲了</p>
              )}
            </div>
          )}
          
          {/* 推荐歌单 */}
          <div className="section-header" style={{ marginTop: '40px' }}>
            <h2>推荐歌单</h2>
          </div>
          
          {/* 歌单错误信息 */}
          {playlistsError && (
            <div className="error-message">
              {playlistsError}
            </div>
          )}
          
          {/* 歌单加载状态 */}
          {playlistsLoading ? (
            <div className="loading-container">
              <div className="loading-spinner"></div>
              <p>加载歌单中...</p>
            </div>
          ) : (
            <div className="playlist-grid">
              {playlists.length > 0 ? (
                playlists.map((playlist) => (
                  <PlaylistItem
                    key={playlist.id}
                    playlist={playlist}
                    mode="grid"
                    actions={[
                      {
                        label: '播放',
                        className: 'btn-play',
                        onClick: (p) => {
                          // 调用从App组件传递的播放歌单函数
                          playPlaylist(p.id)
                        }
                      }
                    ]}
                    onClick={(p) => {
                      // 点击整个歌单卡片的逻辑
                      console.log('查看歌单详情:', p.name)
                    }}
                  />
                ))
              ) : (
                <div className="empty-state">
                  <p>暂无推荐歌单</p>
                </div>
              )}
            </div>
          )}
        </>
      )}

      {/* 添加到歌单模态框组件 */}
      <AddToPlaylistModal
        visible={showAddToPlaylistModal}
        onClose={closeAddToPlaylistModal}
        onAddSuccess={handleAddToPlaylistSuccess}
        selectedSong={selectedSong}
      />
    </div>
  )
}

export default Discover